<template>
  <!-- 筛选区 -->
  <el-card shadow="never" class="henader-card">
    <div class="flx-row">
      <el-form :inline="true" :model="queryForm" style="flex: 1">
        <!-- SN码筛选 -->
        <el-form-item label="SN码：" label-width="120px">
          <el-input
            v-model="queryForm.snCode"
            placeholder="请输入SN码"
            clearable
            class="input-width"
          />
        </el-form-item>

        <!-- 订单编号筛选 -->
        <el-form-item label="订单编号：" label-width="120px">
          <el-input
            v-model="queryForm.orderCode"
            placeholder="请输入订单编号"
            clearable
            class="input-width"
          />
        </el-form-item>
        <!-- 时间范围筛选 -->
        <el-form-item label="时间范围：" label-width="120px">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="datetimerange"
            :shortcuts="shortcuts"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
            style="width: 400px"
          />
        </el-form-item>
         <!-- 每页条数选择 -->
         <el-form-item label="每页条数：" label-width="120px">
          <el-select
            v-model="queryForm.size"
            @change="handleSizeChange"
            style="width: 180px"
          >
            <el-option label="10条/页" value="10" />
            <el-option label="20条/页" value="20" />
            <el-option label="50条/页" value="50" />
            <el-option label="100条/页" value="100" />
          </el-select>
        </el-form-item>

      </el-form>

      <!-- 搜索和导出按钮 -->
      <div class="flex-right">
        <el-button
          type="primary"
          :icon="Search"
          @click="handleQuery"
          class="ml20"
        >
          搜索
        </el-button>
        <el-button
          type="primary"
          :icon="Download"
          @click="exportExcel"
          class="ml20 mr20"
        >
          导出数据
        </el-button>
      </div>
    </div>
  </el-card>

  <!-- 表格和分页部分 -->
  <el-card shadow="never">
    <el-table
      :data="tableData"
      :header-cell-style="{ backgroundColor: '#ecf5ff' }"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <!-- 展开行 -->
      <el-table-column type="expand">
        <template #default="scope">
          <div class="expand-detail">
            <el-descriptions column="1" border>
              <el-descriptions-item label="请求体">
                <pre v-if="scope.row.requestJson">{{ formatJson(scope.row.requestJson) }}</pre>
                <span v-else>无数据</span>
              </el-descriptions-item>
              <el-descriptions-item label="返回体">
                <pre v-if="scope.row.responseJson">{{ formatJson(scope.row.responseJson) }}</pre>
                <span v-else>无数据</span>
              </el-descriptions-item>
              <el-descriptions-item label="详细信息">{{ scope.row.msg || "无" }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </template>
      </el-table-column>

      <!-- 动态表格列 -->
      <el-table-column
        v-for="item in tableColumns"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        :align="item.align"
        :fixed="item.fixed"
        show-overflow-tooltip
      >
        <template #default="scope" v-if="item.prop === 'createTime'">
          <span>{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      small
      background
      :current-page="pagination.page"
      :page-size="pagination.size"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="mt-4"
    />
  </el-card>
</template>

<script setup>
import * as XLSX from "xlsx";
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Search, Download } from "@element-plus/icons-vue"; 
import { getProductionRecords } from "../../../api/modules/index";
import { tableColumns } from "./options.js";

// 1. 筛选表单数据
const queryForm = ref({
  msgType: "不良接口", // 固定为不良接口
  snCode: "",
  orderCode: "",
  dateRange: [],
  page: 1,
  size: 10,
});

// 2. 表格数据和状态
const tableData = ref([]);
const loading = ref(false);
const pagination = ref({
  page: 1,
  size: 10,
  total: 0,
});

// 3. 日期快捷选项
const shortcuts = [
  {
    text: "今天",
    value: () => [
      new Date(new Date().setHours(0, 0, 0, 0)),
      new Date(new Date().setHours(23, 59, 59, 999)),
    ],
  },
  {
    text: "昨天",
    value: () => [
      new Date(new Date().getTime() - 24 * 60 * 60 * 1000),
      new Date(new Date().setHours(23, 59, 59, 999) - 24 * 60 * 60 * 1000),
    ],
  },
  {
    text: "近7天",
    value: () => [
      new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000),
      new Date(),
    ],
  },
];

// 4. 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const formatUTCDate = (date) => {
      if (!date) return "";
      const d = new Date(date);
      return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")} ${String(d.getUTCHours()).padStart(2, "0")}:${String(d.getUTCMinutes()).padStart(2, "0")}:${String(d.getUTCSeconds()).padStart(2, "0")}`;
    };

    const { dateRange, ...restParams } = queryForm.value;
    const params = {
      ...restParams,
      startTime: formatUTCDate(dateRange?.[0]),
      endTime: formatUTCDate(dateRange?.[1]),
      page: queryForm.value.page,
      size: queryForm.value.size,
    };

    const res = await getProductionRecords(params);
    if (res.result === 1) {
      tableData.value = res.data.items || [];
      pagination.value.total = res.data.total || 0;
    } else {
      ElMessage.error(res.message || "获取数据失败");
    }
  } catch (err) {
    ElMessage.error("网络错误，请重试");
  } finally {
    loading.value = false;
  }
};

// 5. 搜索事件
const handleQuery = () => {
  queryForm.value.page = 1;
  loadData();
};

// 6. 分页事件
const handleSizeChange = (size) => {
  queryForm.value.size = size;
  queryForm.value.page = 1;
  pagination.value.size = size;
  loadData();
};

const handleCurrentChange = (page) => {
  queryForm.value.page = page;
  pagination.value.page = page;
  loadData();
};

// 7. 导出Excel功能（与前面报表保持一致）
const exportExcel = () => {
  if (!tableData.value.length) {
    ElMessage.warning("当前没有数据可导出");
    return;
  }

  // 格式化导出数据（匹配表格列）
  const exportData = tableData.value.map(row => ({
    "ID": row.id || "-",
    "SN条码": row.sNcode || "-",
    "订单编号": row.orderCode || "-",
    "消息类型": row.msgType || "-", 
    "工站名称": row.currentStationName || "-",
    "工站编码": row.currentStationCode || "-",
    "排程编号": row.scheduleCode || "-",
    "产线代码": row.lineCode || "-",
    "操作结果": row.currentResult || "-",
    "创建时间": formatDate(row.createTime) || "-",
    "详细信息": row.msg || "-"
  }));

  // 生成Excel并下载
  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "不良报表数据");
  const fileName = `不良报表_${new Date().toLocaleString().replace(/[:/]/g, "-")}.xlsx`;
  XLSX.writeFile(workbook, fileName);

  ElMessage.success("导出成功");
};

// 8. 工具函数
const formatDate = (isoString) => {
  if (!isoString) return "";
  const date = new Date(isoString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

const formatJson = (jsonStr) => {
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2);
  } catch (e) {
    return jsonStr;
  }
};

// 9. 页面初始化
onMounted(() => {
  loadData();
});
</script>

<style lang="scss" scoped>

.henader-card {
  margin-bottom: 20px;
  padding: 15px 20px;
}

:deep(.el-form-item) {
  margin-right: 15px;
  margin-bottom: 10px;
}

.input-width {
  width: 180px;
}

:deep(.el-date-editor) {
  width: 400px;
}

.mt-4 {
  float: right;
  text-align: right;
  margin-top: 20px;
  margin-bottom: 20px;
}

:deep(.el-table .cell) {
  white-space: normal !important;
  word-break: break-all;
  line-height: 1.5;
}

.expand-detail {
  padding: 10px 0;
}

.expand-detail pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  max-height: 300px;
  font-size: 12px;
}

.flx-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.flex-right {
  display: flex;
  align-items: center;
}

.ml20 {
  margin-left: 20px;
}

.mr20 {
  margin-right: 20px;
}
</style>